package com.example._05mvcboot03.controller;

import com.example._05mvcboot03.common.response.JsonResult;
import com.example._05mvcboot03.common.response.StatesCode;
import com.example._05mvcboot03.mapper.UserMapper;
import com.example._05mvcboot03.pojo.dto.UserArticleDTO;
import com.example._05mvcboot03.pojo.dto.UserLoginDTO;
import com.example._05mvcboot03.pojo.entity.Article;
import com.example._05mvcboot03.pojo.vo.ArticleVO;
import com.example._05mvcboot03.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
@Validated
@Api(tags = "用户模块")
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @ApiOperation("登录")
    @PostMapping("login")
    @ApiImplicitParam(name = "userLoginDTO",value = "登录请求对象", required = true,dataType = "UserLoginDTO")
    public JsonResult login (@Validated UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){

        UserVO userVO = userMapper.selectUser(userLoginDTO.getUsername(), userLoginDTO.getPassword());
        if (userVO==null)
            return new JsonResult(StatesCode.USERNAME_PASSWORD_ERROR);
        if(!userVO.getPassword().equals(userLoginDTO.getPassword()))
            return new JsonResult(StatesCode.USERNAME_PASSWORD_ERROR);
        session.setAttribute("user",userVO);
        return JsonResult.ok(userVO);

    }
    @ApiOperation("发表论文")
    @PostMapping("article")
    public JsonResult article(@RequestBody UserArticleDTO userArticleDTO,@ApiIgnore HttpSession session){
        UserVO userVO= (UserVO) session.getAttribute("user");
        if(userVO==null)
            return new JsonResult(StatesCode.NOT_LOGIN);
        Article article = new Article();
        BeanUtils.copyProperties(userArticleDTO,article);
        article.setUserId(userVO.getId());
        userMapper.article(article);
        return JsonResult.ok(article);
    }
    @ApiOperation("根据论文id查论文")
    @GetMapping("selectByArticleId")
    public JsonResult selectByArticleId(@Range(min = 1,max = 100,message = "文章id在1-100之间") @RequestParam Long id){
        ArticleVO articleVO = userMapper.selectByArticleId(id);
        return new JsonResult(StatesCode.OPERATION_SUCCESS,articleVO);
    }
    @ApiOperation("退出登录")
    @PostMapping("remove")
    private JsonResult remove(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
        return JsonResult.ok(StatesCode.OPERATION_SUCCESS);
    }
}
